package com.yzg.study.kafka.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.AbstractRequestLoggingFilter;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter(filterName = "InterfaceTraceFilter", urlPatterns = "/*")
@Component
@Slf4j
public class InterfaceTraceFilter extends AbstractRequestLoggingFilter {

    @Override
    protected void beforeRequest(HttpServletRequest httpServletRequest, String msg) {
        MDC.put("requestId", UUID.randomUUID().toString().replace("-",""));
        MDC.put("startTime", String.valueOf(System.currentTimeMillis()));
    }

    @Override
    protected void afterRequest(HttpServletRequest httpServletRequest, String msg) {
        Long requestTime = System.currentTimeMillis() - Long.parseLong(MDC.get("startTime"));
        log.info("[{}接口请求耗时：{}ms,请求信息为：{}]", httpServletRequest.getRequestURI(), requestTime, msg);
    }
}
